package com.yr.visa.util;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * 仿照spring 解析代码
 *
 */
public class PlaceholderUtils {

	private static Logger logger = LoggerFactory.getLogger(PlaceholderUtils.class);

	/**
	 * Prefix for system property placeholders: "${"
	 */
	public static final String PLACEHOLDER_PREFIX = "${";
	/**
	 * Suffix for system property placeholders: "}"
	 */
	public static final String PLACEHOLDER_SUFFIX = "}";

	public static String resolvePlaceholders(String text,
			Map<String, String> parameter) {
		if (parameter == null || parameter.isEmpty()) {
			return text;
		}
		StringBuffer buf = new StringBuffer(text);
		int startIndex = buf.indexOf(PLACEHOLDER_PREFIX);
		while (startIndex != -1) {
			int endIndex = buf.indexOf(PLACEHOLDER_SUFFIX, startIndex
					+ PLACEHOLDER_PREFIX.length());
			if (endIndex != -1) {
				String placeholder = buf.substring(startIndex
						+ PLACEHOLDER_PREFIX.length(), endIndex);
				int nextIndex = endIndex + PLACEHOLDER_SUFFIX.length();
				try {
					
					if(!parameter.containsKey(placeholder)){
						logger.warn("Could not resolve placeholder '"
								+ placeholder );
					}else{
						String propVal = parameter.get(placeholder);
						propVal=propVal==null?"":propVal;
						buf.replace(startIndex,
								endIndex + PLACEHOLDER_SUFFIX.length(), propVal);
						nextIndex = startIndex + propVal.length();
					}
					
				} catch (Exception ex) {
					logger.warn("Could not resolve placeholder '" + placeholder
							+ ex);
				}
				startIndex = buf.indexOf(PLACEHOLDER_PREFIX, nextIndex);
			} else {
				startIndex = -1;
			}
		}
		return buf.toString();
	}

	public static void main(String[] args) {
		String aa=ClassPathReader.readFromPath("queryTemplate/yc_baojia/2.snap", "UTF-8", true);
		Map<String, String> map = new HashMap<String, String>();
		map.put("transferTime", "bbb");
		map.put("people", "小明");
		System.out.println(PlaceholderUtils.resolvePlaceholders(aa, map));
	}
}
